import app from '@/services/ws/event';

export class WebsokcetOps {
  public ws: WebSocket | undefined;
  public wsUrl: string = '';
  connection(url: string) {
    try {
      this.wsUrl = url;
      const ws = new WebSocket(url);
      //申请一个WebSocket对象，参数是服务端地址，同http协议使用http://开头一样，WebSocket协议的url使用ws://开头，另外安全的WebSocket协议使用wss://开头
      ws.onopen = function () {};
      ws.onmessage = function (e) {
        try {
          const messageJson = JSON.parse(e.data);
          if (messageJson.hasOwnProperty('event')) {
            app.trigger(messageJson['event'], messageJson);
          }
        } catch (e) {
          console.error(e);
        }
      };
      ws.onclose = function (e) {};
      ws.onerror = function (e) {};
      if (this.ws) {
        this.ws.close();
      }
      this.ws = ws;
    } catch (e) {
      console.log(e);
    }
    return this;
  }
  setAutoReconnection() {
    setInterval(() => {
      if (this.wsUrl && this.ws && this.ws.readyState != 1) {
        this.connection(this.wsUrl);
      }
    }, 2000);
  }
}
